﻿using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using Configuration;
using Model;

namespace Repository.Common
{
    public class Repository<T> : IRepository<T> where T : class, IModel
    {
        private Database _context = null;
        private ObjectSet<T> _objectSet;

        public Database GetContext()
        {
            return _context;
        }

        public Repository(Database context)
        {
            _context = context;
            _objectSet = _context.CreateObjectSet<T>();
        }

        public void Insert(T obj)
        {
            this.AddObject(obj);
            this._context.SaveChanges();
        }

        public void Update(T obj)
        {
            //this.AttachObject(obj);
            this._context.SaveChanges();
        }

        public void Delete(T obj)
        {
            this._context.DeleteObject(obj);
            this._context.SaveChanges();
        }

        public List<T> GetAll()
        {
            return _objectSet.OrderBy(o => o.Id).ToList();
        }

        public ObjectQuery<T> GetQuery()
        {
            return _objectSet;
        }

        public void AddObject(T obj)
        {
            _objectSet.AddObject(obj);
        }

        public void AttachObject(T obj)
        {
            _objectSet.Attach(obj);
        }

        public T GetById(int id)
        {
            return _objectSet.SingleOrDefault(e => e.Id == id);
        }

        public List<T> Paging(int pageIndex, int numOfRows)
        {
            var skipRows = (pageIndex - 1) * numOfRows;

            return GetQuery().OrderBy(o => o.Id).ToList().Skip(skipRows).Take(numOfRows).ToList();
        }

        public int GetTotalPage(int numOfRows)
        {
            return GetTotalPage(numOfRows, _objectSet.ToList());
            //return ((int)((double)_objectSet.ToList().Count() / (double)numOfRows)) + 1;
        }

        public int GetTotalPage(int numOfRows, List<T> list)
        {
            var even = _objectSet.ToList().Count() / numOfRows;
            var odd = _objectSet.ToList().Count() % numOfRows;
            if (odd > 0)
                even += 1;

            return even;
        }
    }
}